package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 */
@Service
@Slf4j
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 判断有没有行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        if (apBehaviorEntry == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (apLikesBehavior == null && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())){
            // 点赞
            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            apLikesBehavior.setOperation(ApLikesBehavior.Operation.LIKE.getCode());
            apLikesBehavior.setType((short) 0);
            save(apLikesBehavior);
            return ResponseResult.okResult();
        }else {
            // 取消点赞
            apLikesBehavior.setOperation((short) 1);
            updateById(apLikesBehavior);
            return ResponseResult.okResult();
        }
    }
}
